package com.toman.ui.work.choose;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Enum.BaseEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.LoadingEmptyActivity;
import com.toman.widget.MyListView;
import com.toman.Util.ToastUtil;
import com.toman.bean.ItemListBean;
import com.toman.ui.work.base.RoleInfActivity;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.widget.callback.ErrorCallback;
import com.toman.widget.callback.PostUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class ChooseRoleListEmptyActivity extends LoadingEmptyActivity {

    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.fl_et)
    FrameLayout flEt;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    @BindView(R.id.lv)
    MyListView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    ItemListAdapter adapter;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    int 		totalPage=100;
    int page = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_role_list);
        ButterKnife.bind(this);
        initIntent();
        initView();
//        initList();
        initLoad();


    }

    @Override
    protected Activity getContent() {
        return this;
    }

    @Override
    public void load() {
finish();
    }

    private void initIntent() {
        Bundle data=getIntent().getExtras();//获取数据包

        msg= data != null ? data.getString("msg") : null;
        initToolBar(msg);
        baseEnum=BaseEnum.ROLE;


    }

    private void initView() {
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        adapter=new ItemListAdapter(this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean=adapter.getItem(i);


                        Bundle bundle=new Bundle();
                        bundle.putString("id" ,bean.getID());
                        IntentUtils.startActivity(ChooseRoleListEmptyActivity
                                .this, RoleInfActivity.class,bundle);





            }
        });
        customer(1,1,"");

        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //getHttp(1,1);
                page=2;
                customer(1, 1, etSearch.getText().toString().trim());


            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, etSearch.getText().toString().trim());
                page += 1;



            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                customer(1, 1, s.toString().trim());

            }
        });
    }


    /*
      企业列表
   */
    public void customer(Integer page, final Integer type, String search) {


        OkHttpUtils
                .get(NewBaseUrl.role_list_get)
                .params("token", token)
                .params("companyId",getIntent().getStringExtra("id"))
                .params("key", search)
                .params("limit", NewBaseUrl.num)
                .params("page", page.toString())

                .execute(new StringCallback() {

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                        PostUtil.postCallbackDelayed(loadService, ErrorCallback.class);
                    }

                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "角色列表: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code =jsonObj.getInteger("code");
                        ViewUtil.lagout(code,getApplicationContext());

                        if (code==0){
                            JSONObject Jpage=jsonObj.getJSONObject("page");
                            totalPage=Jpage.getIntValue("totalPage");
                            JSONArray jsonArray=Jpage.getJSONArray("list");
                            for (int i=0; i<jsonArray.size();i++)
                            {
                                ItemListBean bean = new ItemListBean( jsonArray.getJSONObject(i).getString("roleName"),jsonArray.getJSONObject(i).getString("roleId"));
                                list.add(bean);
                            }
                            adapter.refreshData(list);
                       isEmpty(list,mMangeNodata);
                            adapter.notifyDataSetChanged();
                        }

                        else {
                            ToastUtil.makeText(getApplicationContext(),jsonObj.getString("msg"));
                        }

                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                });
    }
}
